//
//  LineTextField.m
//  BCNADemo
//
//  Created by 马东朝 on 2018/4/23.
//  Copyright © 2018年 马东朝. All rights reserved.
//

#import "LineTextField.h"
#define colorNum 210
@interface LineTextField ()<UITextFieldDelegate>
{
    TextWay textWay;
    NSTimer *timer;
}
@end
static int codetime = 60;
static NSInteger isShow = 0;
@implementation LineTextField

- (instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        selfFrame = frame;
        isShow = 0;
        [self addSubview:self.areatn];
        [self addSubview:self.textField];
        [self addSubview:self.lineView];
        [self addSubview:self.codeBtn];
        [self addSubview:self.showBtn];
        
    }
    return self;
}
- (UIButton *)areatn{
    if (!_areatn) {
        _areatn = [UIButton buttonWithType:UIButtonTypeCustom];
        _areatn.frame = CGRectMake(0, 0, kWidth(144), kHeight(76));
        _areatn.center = CGPointMake(kWidth(144)/2, self.frame.size.height/2);
        _areatn.layer.cornerRadius = kHeight(5);
        _areatn.layer.masksToBounds = YES;
        [_areatn setTitle:@"+86" forState:UIControlStateNormal];
        [_areatn setTitleColor:[UIColor colorWithHexString:@"#0e0e19"] forState:UIControlStateNormal];
        _areatn.titleLabel.font = [UIFont systemFontOfSize:kHeight(40)];
        _areatn.backgroundColor = [UIColor colorWithHexString:@"#ffffff"];
        [_areatn setTitleColor:[UIColor colorWithHexString:@"#0e0e19"] forState:UIControlStateNormal];
        [_areatn addTarget:self action:@selector(handleSeleArea:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _areatn;
}
- (UITextField *)textField{
    if (!_textField) {
        _textField = [[UITextField alloc] initWithFrame:CGRectMake(CGRectGetMaxX(self.areatn.frame) + kWidth(15), 0, selfFrame.size.width - CGRectGetWidth(self.areatn.frame) - kWidth(15), kHeight(76))];
        _textField.delegate = self;
        _textField.font = [UIFont systemFontOfSize:kHeight(40)];
        _textField.textColor = [UIColor whiteColor];
        _textField.delegate = self;
        UIButton *button = [_textField valueForKey:@"_clearButton"];
        [button setImage:[UIImage imageNamed:@"icon_blueclear@3x.png"] forState:UIControlStateNormal];
        [button setImage:[UIImage imageNamed:@"icon_blueclear@3x.png"] forState:UIControlStateHighlighted];
        
        [_textField setSecureTextEntry:NO];
    _textField.clearButtonMode=UITextFieldViewModeWhileEditing;
    }
    return _textField;
}
- (UIButton *)codeBtn{
    if (!_codeBtn) {
        _codeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _codeBtn.backgroundColor = [UIColor whiteColor];
        _codeBtn.layer.cornerRadius = kHeight(60);
        _codeBtn.layer.masksToBounds = YES;
        [_codeBtn setTitle:StringWithKey(@"LFView4") forState:UIControlStateNormal];
        [_codeBtn setTitleColor:[UIColor colorWithHexString:@"#0e0e19"] forState:UIControlStateNormal];
        _codeBtn.titleLabel.font = [UIFont systemFontOfSize:kHeight(40)];
        [_codeBtn addTarget:self action:@selector(handleGetVerCode:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _codeBtn;
}
- (UIButton *)showBtn{
    if (!_showBtn) {
        _showBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_showBtn setImage:[UIImage imageNamed:@"mimabukejian@3x.png"] forState:UIControlStateNormal];
        [_showBtn addTarget:self action:@selector(handleShowPassword:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _showBtn;
}
- (UIView *)lineView{
    if (!_lineView) {
        _lineView = [[UIView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.textField.frame) + kHeight(30), selfFrame.size.width, 1.0)];
        _lineView.backgroundColor = [UIColor colorWithHexString:@"#6e7084"];
    }
    return _lineView;
}

- (void)resignFirstResponder{
    
    [self chectTextFieldString:self.textField];
    
}
#pragma  mark -- UITextFieldDelegate

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    
    return YES;
}
#pragma mark -- 
- (void)setTextConentStyleWith:(TextWay)textway{
    textWay = textway;
    switch (textway) {
        case TextWayEmail:
        {
            _textField.keyboardType = UIKeyboardTypeEmailAddress;
            _areatn.frame = CGRectMake(0, 0, 0, 0);
            _textField.text = @"";
            _textField.frame = CGRectMake(CGRectGetMaxX(self.areatn.frame) + kWidth(15), 0, selfFrame.size.width - CGRectGetWidth(self.areatn.frame) - kWidth(15), kHeight(76));
            
            
            [self setPalaceHolderWithStr:StringWithKey(@"LFView0")];
            _showBtn.frame = CGRectMake(0, 0, 0, 0);
            _codeBtn.frame = CGRectMake(0, 0, 0, 0);
        }
            break;
        case TextWayIphoneNumber:
        {
            _textField.keyboardType = UIKeyboardTypeNumberPad; 
            [[NSUserDefaults standardUserDefaults] setValue:@"86" forKey:CodeStr];
            _textField.text = @"";
            _areatn.frame = CGRectMake(0, 0, kWidth(144), kHeight(76));
            _textField.frame = CGRectMake(CGRectGetMaxX(self.areatn.frame) + kWidth(15), 0, selfFrame.size.width - CGRectGetWidth(self.areatn.frame) - kWidth(15), kHeight(76));
            
            
            
            [self setPalaceHolderWithStr: StringWithKey(@"LFView1")];
            
            _showBtn.frame = CGRectMake(0, 0, 0, 0);
            _codeBtn.frame = CGRectMake(0, 0, 0, 0);
            
        }
            break;
        case TextWayVerificationCode:
        {
           _textField.keyboardType = UIKeyboardTypeNumberPad;
            _areatn.frame = CGRectMake(0, 0, 0, 0);
            _textField.frame = CGRectMake(CGRectGetMaxX(self.areatn.frame) + kWidth(15), 0, selfFrame.size.width - CGRectGetWidth(self.areatn.frame) - kWidth(15)-kWidth(280), kHeight(76));
            _showBtn.frame = CGRectMake(0, 0, 0, 0);
            CGFloat width  = 0.f;
            if ([lanagueStyle isEqualToString:@"China"]) {
                width = kWidth(270);
            }else{
                width = kWidth(420);
            }
            _codeBtn.frame = CGRectMake(0, 0, width, kHeight(120));
            _codeBtn.center = CGPointMake(selfFrame.size.width - width/2, _textField.center.y);
            [self setPalaceHolderWithStr:StringWithKey(@"LFView2")];
        }
            break;
        case TextWayPassWord:
        {
          [_textField setSecureTextEntry:YES]; _textField.clearButtonMode=UITextFieldViewModeNever;
            _areatn.frame = CGRectMake(0, 0, 0, 0);
            _textField.frame = CGRectMake(CGRectGetMaxX(self.areatn.frame) + kWidth(15), 0, selfFrame.size.width - CGRectGetWidth(self.areatn.frame) - kWidth(15)-kWidth(25), kHeight(76));
            
            
            [self setPalaceHolderWithStr:StringWithKey(@"LFView3")];
            _codeBtn.frame = CGRectMake(0, 0, 0, 0);
            _showBtn.frame = CGRectMake(0, 0, kWidth(64), kWidth(29));
            _showBtn.center = CGPointMake(selfFrame.size.width - kWidth(50), _textField.center.y+ kWidth(29/2));
        }
            break;
            
        default:
            break;
    }
}
- (void)setPalaceHolderWithStr:(NSString *)placeHolder{
    NSMutableDictionary *attrs = [NSMutableDictionary dictionary];
    attrs[NSForegroundColorAttributeName] = [UIColor colorWithHexString:@"6e7084"];
    //NSAttributedString:带有属性的文字（叫富文本，可以让你的文字丰富多彩）但是这个是不可变的带有属性的文字，创建完成之后就不可以改变了  所以需要可变的
    NSMutableAttributedString *placeHolders = [[NSMutableAttributedString alloc]initWithString:placeHolder attributes:attrs];
    _textField.attributedPlaceholder = placeHolders;
}
#pragma mark --  按钮点击事件
///选择手机区号
- (void)handleSeleArea:(UIButton *)sender{
    SelectAreaController *vc = [[SelectAreaController alloc]init] ;
    vc.hidesBottomBarWhenPushed = YES ;
    vc.returnCountryCodeBlock = ^(NSString *countryCodeStr) {
        [sender setTitle:countryCodeStr forState:UIControlStateNormal];
        NSString *codeStr = [countryCodeStr stringByReplacingOccurrencesOfString:@"+" withString:@""];
        
        [[NSUserDefaults standardUserDefaults] setValue:codeStr forKey:CodeStr];
    };
    [[self viewController].navigationController pushViewController:vc animated:YES] ; //通过找到的控制器进行跳转
}
- (UIViewController *)viewController {
    for (UIView* next = [self superview]; next; next = next.superview) {
        UIResponder *nextResponder = [next nextResponder];
        if ([nextResponder isKindOfClass:[UIViewController class]]) {
            return (UIViewController *)nextResponder;
        }
    }
    return nil;
}
///显示密码可见
- (void)handleShowPassword:(UIButton *)sender{
    if (isShow == 1) {
        isShow = 0;
        sender.frame = CGRectMake(0, 0, kWidth(64), kWidth(29));
        sender.center = CGPointMake(selfFrame.size.width - kWidth(50), _textField.center.y+ kWidth(29/2));
        [_showBtn setImage:[UIImage imageNamed:@"mimabukejian@3x.png"] forState:UIControlStateNormal];
        [_textField setSecureTextEntry:YES];
        
        
    }else{
        isShow =1;
        sender.frame = CGRectMake(0, 0, kWidth(62), kWidth(42));
        sender.center = CGPointMake(selfFrame.size.width - kWidth(50), _textField.center.y);
        [_showBtn setImage:[UIImage imageNamed:@"mimakejian@3x.png"] forState:UIControlStateNormal];
        [_textField setSecureTextEntry:NO];
        
    }
}
- (void)postSMSCodeWithPhoneDic:(NSMutableDictionary *)phoneDic{
    NSLog(@"%@", phoneDic);
    [GLHttpTool post:[NSString stringWithFormat:@"%@/sms/send", UrlAddress] params:phoneDic success:^(id responseObj) {
        NSLog(@"responseObj==%@", responseObj);
        NSString *code = [NSString stringWithFormat:@"%@", responseObj[@"code"]];
        NSString *msg = [NSString stringWithFormat:@"%@", responseObj[@"msg"]];
        if ([code isEqualToString:@"200"]) {
            
            
            
        }else{
            
            AlterView(StringWithKey(@"ALter0"), msg, StringWithKey(@"ALter8"));
            
        }
    } failure:^(NSError *error) {
        NSLog(@"error==%@", error);
    }];
}
///获取验证码
- (void)handleGetVerCode:(UIButton *)sender{
    
//    [self openCountdown];
    if ([self.delegate respondsToSelector:@selector(handleGetSMSCode)]) {
        [self.delegate handleGetSMSCode];
    }else{
        NSLog(@"2222");
    }
    timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(openCountdown) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
}
// 开启倒计时效果
-(void)openCountdown{
    
   

    if (codetime == 0) {
        [timer invalidate];
        timer = nil;
        codetime = 60;
        //设置按钮的样式
        [self.codeBtn setTitle:StringWithKey(@"RegistVC6") forState:UIControlStateNormal];
        [self.codeBtn setTitleColor:[UIColor colorWithHexString:@"#40b5f8"] forState:UIControlStateNormal];
        self.codeBtn.userInteractionEnabled = YES;
        
    }else{
        int seconds = codetime;// % 60;
    
                
                //设置按钮显示读秒效果
                [self.codeBtn setTitle:[NSString stringWithFormat:@"%@(%.2ds)", StringWithKey(@"RegistVC6"), seconds] forState:UIControlStateNormal];
                [self.codeBtn setTitleColor:[UIColor colorWithHexString:@"#979797"] forState:UIControlStateNormal];
                self.codeBtn.userInteractionEnabled = NO;
            
            codetime--;
    }
    
}
#pragma mark -- UITextFieldDelegate


- (void)chectTextFieldString:(UITextField *)textField{
    
    switch (textWay) {
        case TextWayIphoneNumber:
        {
            NSString * regex = @"^[0-9]{1,100}$";
            NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
            BOOL isMatch = [pred evaluateWithObject:textField.text];
            if (isMatch == YES) {
                self.returnRight = YES;
            }else{
                if (textField.text.length == 0) {
                    AlterView(StringWithKey(@"ALter0"), StringWithKey(@"ALter7"), StringWithKey(@"ALter8"));
                }else{
                    AlterView(StringWithKey(@"ALter0"), StringWithKey(@"ALter6"), StringWithKey(@"ALter8"));
                }
            }
            
            
        }
            break;
        case TextWayVerificationCode:
        {
            if (textField.text.length == 0) {
                AlterView(StringWithKey(@"ALter0"), StringWithKey(@"ALter4"), StringWithKey(@"ALter8"));
            }else if (textField.text.length > 6){
                AlterView(StringWithKey(@"ALter0"), StringWithKey(@"ALter5"), StringWithKey(@"ALter8"));
            }else{
                self.returnRight = YES;
            }
            
        }
            break;
        case TextWayEmail:
        {
            if (textField.text.length == 0) {
                AlterView(StringWithKey(@"ALter0"), StringWithKey(@"ALter3"), StringWithKey(@"ALter8"));
            }else{
                BOOL right = [self isValidateEmail:textField.text];
                if (right == YES) {
                   self.returnRight = YES;
                }else{
                    AlterView(StringWithKey(@"ALter0"), StringWithKey(@"ALter10"), StringWithKey(@"ALter8"));
                }
                
            }
            //            if (textField.text.length > 4) {
            //                NSString *subStr = [textField.text substringFromIndex:textField.text.length-4];
            //                NSLog(@"%@", subStr);
            //                if ([subStr isEqualToString:@".com"]) {
            //                    NSLog(@"邮箱格式正确");
            //                }else{
            //                    NSLog(@"邮箱格式不正缺");
            //                }
            //            }else{
            //                 NSLog(@"邮箱格式不正缺");
            //            }
            
        }
            break;
        case TextWayPassWord:
        {
            NSString * regex = @"^[A-Za-z0-9]{8,20}$";
            NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
            BOOL isMatch = [pred evaluateWithObject:textField.text];
            
            if (isMatch == YES) {
                //2.block传值
                
                self.returnRight = YES;
                
            }else{
                
                if (textField.text.length == 0) {
                    AlterView(StringWithKey(@"ALter0"), StringWithKey(@"ALter1"), StringWithKey(@"ALter8"));
                }else{
                    AlterView(StringWithKey(@"ALter0"), StringWithKey(@"ALter2"),StringWithKey(@"ALter8"));
                    
                }
            }
        }
            break;
            
            
        default:
            break;
    }
}
//邮箱地址的正则表达式
- (BOOL)isValidateEmail:(NSString *)email{
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:email];
}


@end
